package com.example.sprintboot.controller;

import com.example.sprintboot.common.Result;
import com.example.sprintboot.entity.Cart;
import com.example.sprintboot.entity.CreateOrderRequest;
import com.example.sprintboot.entity.Order;
import com.example.sprintboot.service.CartService;
import com.example.sprintboot.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
@CrossOrigin
public class OrderController {
    @Resource
    private OrderService orderService;

    @Resource
    private CartService cartService;

    @PostMapping("/create")
    public Result createOrder(@RequestBody CreateOrderRequest request) {
        // 获取用户购物车中的商品
        List<Cart> cartItems = cartService.selectAll().stream()
                .filter(item -> item.getUserId().equals(request.getUserId()))
                .toList();

        if (cartItems.isEmpty()) {
            return Result.error("购物车为空");
        }

        // 创建订单
        Order order = orderService.createOrder(request.getUserId(), cartItems);
        return Result.success(order);
    }

    @GetMapping("/user/{userId}")
    public Result getUserOrders(@PathVariable Integer userId) {
        List<Order> orders = orderService.getUserOrders(userId);
        return Result.success(orders);
    }

    @GetMapping("/{orderId}")
    public Result getOrderById(@PathVariable Integer orderId) {
        Order order = orderService.getOrderById(orderId);
        return Result.success(order);
    }
} 